package io.kiki.sba.registry.server.clientInterface.converter.pb;


import io.kiki.sba.registry.common.model.client.pb.MetaRegister;
import io.kiki.sba.registry.common.model.client.pb.MetaService;
import io.kiki.sba.registry.common.model.client.pb.StringList;
import io.kiki.sba.registry.common.model.store.AppRevision;
import io.kiki.sba.registry.core.model.AppRevisionInterface;

import java.util.*;
import java.util.Map.Entry;


public final class AppRevisionConvertor {
    private AppRevisionConvertor() {
    }

    public static AppRevision convert2Java(MetaRegister metaRegister) {
        AppRevision revision = new AppRevision();
        String appName = metaRegister.getApplication();
        revision.setAppName(appName);
        revision.setRevision(metaRegister.getRevision());
        revision.setClientVersion(metaRegister.getClientVersion());

        Map<String, List<String>> baseParams = new HashMap<>(metaRegister.getBaseParamsMap().size());
        for (Entry<String, StringList> entry : metaRegister.getBaseParamsMap().entrySet()) {
            List<String> v = new ArrayList<>(entry.getValue().getValuesList());
            baseParams.put(entry.getKey(), v);
        }
        revision.setBaseParams(baseParams);

        Map<String, AppRevisionInterface> interfaceMap = new HashMap<>(metaRegister.getServicesMap().size());
        for (Entry<String, MetaService> entry : metaRegister.getServicesMap().entrySet()) {
            interfaceMap.put(entry.getKey(), MetaServiceConvertor.convert2Java(entry.getValue()));
        }
        revision.setInterfaceMap(interfaceMap);
        revision.setSize(metaRegister.getSerializedSize());
        return revision;
    }

    public static MetaRegister convert2Pb(AppRevision appRevision) {
        MetaRegister.Builder builder = MetaRegister.newBuilder();

        builder.setApplication(appRevision.getAppName());
        builder.setRevision(appRevision.getRevision());

        for (Entry<String, List<String>> entry : Optional.ofNullable(appRevision.getBaseParams()).orElse(Collections.emptyMap()).entrySet()) {
            StringList.Builder listBuilder = StringList.newBuilder().addAllValues(entry.getValue());
            builder.putBaseParams(entry.getKey(), listBuilder.build());
        }

        for (Entry<String, AppRevisionInterface> entry : Optional.ofNullable(appRevision.getInterfaceMap()).orElse(Collections.emptyMap()).entrySet()) {
            builder.putServices(entry.getKey(), MetaServiceConvertor.convert2Pb(entry.getValue()));
        }
        return builder.build();
    }
}
